package com.glamour.hlcity.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.glamour.hlcity.common.exception.BizException;

/**
 * 转换成map的工具类
 * @author zhaoxing.liuzx
 *
 */
public class MapUtil {
	
	public static Map<String,String> toMap(Object obj){
		Map<Field,Object> fieldMap=new HashMap<Field,Object> ();
		filedList(obj, obj.getClass(), fieldMap);
		return mapToMap(fieldMap);
	}
	/**
	 * Map转换
	 * @param fieldMap
	 * @return
	 */
	private static Map<String,String> mapToMap(Map<Field,Object> fieldMap){
		Map<String,String> map=new HashMap<String, String>();
		Set<Entry<Field, Object>> set=fieldMap.entrySet();
		Iterator<Entry<Field, Object>> iter=set.iterator();
		for(;iter.hasNext();){
			Entry<Field, Object> entry=iter.next();
			map.put(entry.getKey().getName(), entry.getValue()==null?"":entry.getValue().toString());
		}
		return map;
	}
	
	
	private static void filedList(Object obj,Class clazz,Map<Field,Object> fieldList){
		
		if(fieldList==null){
			throw new BizException("filedList can not be null", new RuntimeException());
		}
		if(clazz==null){
			return;
		}
		if(clazz.equals(Object.class)){
			return;
		}else{
			List<Field> fields=ListUtil.toList(clazz.getDeclaredFields());
			for(Field field:fields){
				try {
					@SuppressWarnings("unchecked")
					Object value=clazz.getMethod(StringUtil.prefixMethod("get", field.getName())).invoke(obj);
					if(value!=null){
						fieldList.put(field, value);	
					}else{
						fieldList.put(field, "");
					}
					
				} catch (IllegalArgumentException e) {
					
				} catch (SecurityException e) {
					
				} catch (NoSuchMethodException e) {
					
				} catch (IllegalAccessException e) {
				
				
				} catch (InvocationTargetException e) {
					
				}
			}
			
			Class parentClazz=clazz.getSuperclass();
			filedList(obj, parentClazz, fieldList);
		}
	}
	

}
